import config
import json
import random
from utils import *

def register():
	return RandomCET4()

class RandomCET4:
	def __init__(self):
		self.type = 'passive'
		with open(config.bubbles.randomCET4.file) as f:
			self.table = json.loads(f.read())
		self.help = \
'''随机四级：
	用法：
		*随机四级
		*随机四级 (数量)
	随机生成四级英文单词和释义。'''

	def randomWords(self, count = config.bubbles.randomCET4.count):
		words = random.sample(self.table, k = count)
		return { word: meanings for word, *meanings in words }

	def makeMsg(self, d, offset = 0):
		chain = MsgChain()
		i = 1 + offset
		for key, val in d.items():
			chain.addPlain(f'{i}. {key}\n')
			i += 1
			for line in val:
				chain.addPlain(f'\t{line}\n')
		return chain

	def run(self, gum, msg):
		if not msg['type'] in ['FriendMessage', 'GroupMessage'] \
				or len(msg['messageChain']) <= 1 \
				or msg['messageChain'][1]['type'] != 'Plain' \
				or msg['messageChain'][1]['text'].split()[0] != '*随机四级':
			return
		splitted = msg['messageChain'][1]['text'].split()
		count = config.bubbles.randomCET4.count
		if len(splitted) > 1 and splitted[1].isdigit():
			count = int(splitted[1])
		count = max(count, 1)
		count = min(count, 15)

		d = self.randomWords(count)
		chain = self.makeMsg(d)

		autoReply(chain, gum)